package com.lcf.study.offer;

import com.lcf.study.Util;
import com.lcf.study.model.ListNode;

/**
 * Created by 哈兹米
 * on 2022/9/7
 * Description：
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 * 输入：l1 = [1,2,4], l2 = [1,3,4]
 * 输出：[1,1,2,3,4,4]
 * 输入：l1 = [], l2 = []
 * 输出：[]
 * 输入：l1 = [], l2 = [0]
 * 输出：[0]
 *
 * @see <a href="https://leetcode.cn/problems/merge-two-sorted-lists/">mergeTwoLists</a>
 */
public class _21_mergeTwoLists {

    public static void main(String[] args) {
        _21_mergeTwoLists mergeTwoLists = new _21_mergeTwoLists();
        ListNode listNode1 = new ListNode(1);
        listNode1.next = new ListNode(2);
        listNode1.next.next = new ListNode(4);

        ListNode listNode2 = new ListNode(1);
        listNode2.next = new ListNode(3);
        listNode2.next.next = new ListNode(4);
        listNode2.next.next.next = new ListNode(5);

        ListNode resultNode = mergeTwoLists.mergeTwoLists(listNode1, listNode2);
        Util.printListNode(resultNode);
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode preHead = new ListNode(-1);
        ListNode prev = preHead;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                prev.next = list1;
                list1 = list1.next;
            } else {
                prev.next = list2;
                list2 = list2.next;
            }
            prev = prev.next;
        }
        prev.next = list1 == null ? list2 : list1;
        return preHead.next;
    }
}
